<script setup lang="ts">

import {onMounted, ref} from "vue";
import {UserQueryCriteria, UserVo, DikeQueryCriteria, PageDike, Dike} from "/@/api/openapi";
import {useUserStore} from "/@/store";
import type {UploadProps, UploadRawFile} from 'element-plus'

const tableRef = ref()
const searchParams = ref<DikeQueryCriteria>({
    pageNum: 1,
    pageSize: 5
});

const total = ref<number>(0);
const store = useUserStore();

onMounted(() => {
    if (store.isSign) {
        loadData();
    }
})

const currentUid = ref<number>(-1);
import {DikeService} from "/@/api/openapi";
import {ElMessage, genFileId, UploadInstance, UploadUserFile} from "element-plus";
import {base64ConvertFile, convertFileToBase64} from "/@/utils/convert";
import {Search} from "@element-plus/icons-vue";

const tableData = ref<Array<UserVo>>();
const loadData = () => {
    console.log("点击了loadData")
    DikeService.queryDikeAll(searchParams.value).then((res) => {
        console.log(res)
        ElMessage.success(res)
        if (res.code === 200 && res.data !== null && res.data?.records !== null) {
            tableData.value = res.data?.records
            if (res.data?.total !== undefined) {
                total.value = res.data?.total;
            }
        }
    }, (error) => {
        ElMessage.error(error)
    }).catch((error) => {
        ElMessage.error(error)
    })
}

const centerDialogVisible = ref<boolean>(false)
const addDialogVisible = ref<boolean>(false)
const handleCurrentChange = (val: number) => {
    searchParams.value.pageNum = val
    loadData()
}


const deleteVisible = (data: any) => {
    // 选择了删除按钮
    currentUid.value = data.id;
    centerDialogVisible.value = true
}

const editUid = ref<number>(-1);

const editVisible = (data: any) => {
    // 选择编辑按钮
    upload.value!.clearFiles()
    choose.value = 2;
    editUid.value = data.id;
    addDialogVisible.value = true
    addData.value.id = data.id
}

const addVisible = () => {
    // 选择新增按钮

    choose.value = 1
    addData.value = {
        name: "",
        longitude: 0,
        latitude: 0,
        local: "",
        riverName: "",
        image: "",
    }
    addDialogVisible.value = true
    upload.value!.clearFiles()
}

const addData = ref<Dike>({
    name: "",
    longitude: 0,
    latitude: 0,
    local: "",
    riverName: "",
    image: "",
})

const deleteUser = () => {
    if (currentUid.value === -1) {
        ElMessage.error("请先选择大坝")
    }
    DikeService.deleteDike(currentUid.value).then((res) => {
        if (res.code === 200) {
            ElMessage.success(res.message)
        } else {
            ElMessage.error(res.message)
        }
        loadData()
    }, (error) => {
        ElMessage.error(error)
    }).catch((error) => {
        ElMessage.error(error)
    }).finally(() => {
        centerDialogVisible.value = false
    })
}

const on_change = async (files: File[], uploadFiles: UploadUserFile[]) => {
    if (uploadFiles[0].raw !== undefined) {
        addData.value.image = await convertFileToBase64(uploadFiles[0].raw);
    }

}
const upload = ref<UploadInstance>()
const on_exceed = async (files: File[], uploadFiles: UploadUserFile[]) => {
    console.log("当超出限制时，执行的钩子函数")
    if (files[0] !== undefined) {
        addData.value.image = await convertFileToBase64(files[0]);
    }

    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)

}

const choose = ref<number>(1);
const convert = (base: string) => {
    // console.log("上传了结果" + base)
    const file: File = base64ConvertFile(base, "1.jpg")
    return URL.createObjectURL(file)
}
const submit = async () => {
    console.log("开始上传")
    console.log(addData.value)
    if (addData.value.image === null || addData.value.image === undefined || addData.value.image === "") {
        ElMessage.error("图片还未上传")
        return
    }
    if (addData.value.name === null || addData.value.name === undefined) {
        ElMessage.error("大坝名称")
        return
    }
    if (addData.value.latitude === null || addData.value.latitude === undefined) {
        ElMessage.error("经纬度未填写")
        return
    }
    if (addData.value.longitude === null || addData.value.longitude === undefined) {
        ElMessage.error("经纬度未填写")
        return
    }
    // 如果 选择1 表示新增
    if (choose.value === 1) {
        DikeService.addDike(addData.value).then((res) => {
            if (res.code === 200) {
                ElMessage.success(res.message)
                loadData()
            }
        }, (error) => {
            console.log("reject错误")
            ElMessage.error("错误")
        }).catch((error) => {
            console.log("错误")
            ElMessage.error(error)
        }).finally(() => {
            addDialogVisible.value = false
        })
    } else if (choose.value === 2) {
        DikeService.updateDike(addData.value).then((res) => {
            if (res.code === 200) {
                ElMessage.success(res.message)
                loadData()
            }
        }, (error) => {
            console.log("reject错误")
            ElMessage.error("错误")
        }).catch((error) => {
            console.log("错误")
            ElMessage.error(error)
        }).finally(() => {
            addDialogVisible.value = false
        })
    }
}
</script>

<template>
    <div class="dike">

        <el-row>
            <el-col :span="12" class="grid-cell">
                <el-button @click="loadData" class="flesh">刷新</el-button>
                <el-button @click="addVisible" class="flesh">新增</el-button>
            </el-col>
            <el-col :span="12" class="grid-cell">
                <el-input
                        v-model="searchParams.name"
                        placeholder="搜索大坝名称"
                        class="input-with-select"
                >
                    <template #append>
                        <el-button @click="loadData" :icon="Search"/>
                    </template>
                </el-input>
            </el-col>
        </el-row>


        <el-table border height="600" max-height="600" :ref="tableRef" :data="tableData" style="width: 100%">
            <el-table-column prop="name" label="大坝名称" width="180"/>
            <el-table-column prop="longitude" label="大坝经度" width="250"/>
            <el-table-column prop="latitude" label="大坝纬度" width="180"/>
            <el-table-column prop="local" label="大坝所在地" width="180"/>
            <el-table-column prop="riverName" label="大坝所在河流/水库" width="180"/>
            <el-table-column label="大坝图片">
                <template #default="scope">
                    <el-image
                            :zoom-rate="1.2"
                            :max-scale="7"
                            :min-scale="0.2"
                            style="width: 100px; height: 80px"
                            fit="cover"
                            :src="convert(scope.row.image)"/>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click.prevent="editVisible(scope.row)">编辑大坝
                    </el-button>
                    <el-button link type="primary" size="small" @click.prevent="deleteVisible(scope.row)">删除大坝
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pager-wrapper">
            <el-pagination
                    background
                    layout="prev, pager, next, jumper"
                    :total="total"
                    :page-size="searchParams.pageSize"
                    :current-page="searchParams.pageNum"
                    @current-change="handleCurrentChange"
            />
        </div>

        <el-dialog
                v-model="centerDialogVisible"
                title="提示"
                width="30%"
                align-center
        >
            <span>是否删除该大坝</span>
            <template #footer>
      <span class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="deleteUser">
          确认
        </el-button>
      </span>
            </template>
        </el-dialog>


        <el-dialog
                v-model="addDialogVisible"
                title="提示"
                width="30%"
                align-center
        >
            <el-form :model="addData" ref="vForm" label-position="left" label-width="100px"
                     size="default" @submit.prevent>
                <el-form-item label="大坝名称" prop="name">
                    <el-input v-model="addData.name" type="text" clearable></el-input>
                </el-form-item>
                <el-form-item label="大坝经度" prop="longitude">
                    <el-input v-model="addData.longitude" type="text" clearable></el-input>
                </el-form-item>
                <el-form-item label="大坝纬度" prop="latitude">
                    <el-input v-model="addData.latitude" type="text" clearable></el-input>
                </el-form-item>
                <el-form-item label="大坝所在地" prop="local">
                    <el-input v-model="addData.local" type="text" clearable></el-input>
                </el-form-item>
                <el-form-item label="大坝所在河流" prop="riverName">
                    <el-input v-model="addData.riverName" type="text" clearable></el-input>
                </el-form-item>
                <el-form-item label="大坝图片" prop="image">
                    <el-upload
                            ref="upload"
                            list-type="picture-card"
                            :on-change="on_change"
                            :on-exceed="on_exceed"
                            show-file-list
                            action="#"
                            :auto-upload="false"
                            :limit="1">
                        <template #default><i class="el-icon-plus"></i></template>
                    </el-upload>
                </el-form-item>

                <el-row>
                    <el-col :span="4" class="grid-cell">
                        <div class="static-content-item">
                            <el-button @click="submit" type="primary">确认</el-button>
                        </div>
                    </el-col>
                    <el-col :span="4" class="grid-cell">
                        <div class="static-content-item">
                            <el-button>重置</el-button>
                        </div>
                    </el-col>
                </el-row>

            </el-form>

        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.dike {
    padding: 30px;
    overflow: auto;

    .flesh {
        margin-bottom: 20px;
    }

    .pager-wrapper {
        margin-top: 10px;
    }
}
</style>